package org.dromara.common.core.utils;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.HashMap;
import java.util.Map;

/**
 * @author shuai.zhou
 * @date 2025-07-30 13:31
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ThreadLocalUtils {

    private static final ThreadLocal<Map<String, Object>> THREAD_LOCAL_MAP = ThreadLocal.withInitial(HashMap::new);

    /**
     * 设置上下文参数
     */
    public static void set(String key, Object value) {
        THREAD_LOCAL_MAP.get().put(key, value);
    }

    /**
     * 获取字符串类型上下文参数
     */
    public static String getAsString(String key) {
        Object value = THREAD_LOCAL_MAP.get().get(key);
        return value != null ? String.valueOf(value) : null;
    }

    /**
     * 获取上下文参数
     */
    public static <T> T get(String key, Class<T> clazz) {
        return clazz.cast(THREAD_LOCAL_MAP.get().get(key));
    }

    /**
     * 获取上下文快照（用于异步传递）
     */
    public static Map<String, Object> getThreadLocalMap() {
        return THREAD_LOCAL_MAP.get();
    }

    /**
     * 设置上下文快照（用于异步恢复）
     */
    public static void setThreadLocalMap(Map<String, Object> hashMap) {
        THREAD_LOCAL_MAP.set(hashMap);
    }

    /**
     * 清除当前线程上下文
     */
    public static void clear() {
        THREAD_LOCAL_MAP.remove();
    }

}
